<template>
  <div class="logs-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h2>访问日志</h2>
        <p>查看代理服务器的访问日志和统计信息</p>
      </div>
      <div class="page-actions">
        <el-button @click="exportLogs">
          <el-icon><Download /></el-icon>
          导出日志
        </el-button>
        <el-button @click="refreshLogs">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="代理服务器">
              <el-select
                v-model="searchForm.proxyId"
                placeholder="选择代理"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="proxy in proxies"
                  :key="proxy.id"
                  :label="proxy.name"
                  :value="proxy.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="客户端IP">
              <el-input
                v-model="searchForm.clientIp"
                placeholder="输入IP地址"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="请求方法">
              <el-select
                v-model="searchForm.method"
                placeholder="选择方法"
                clearable
                style="width: 100%"
              >
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
                <el-option label="HEAD" value="HEAD" />
                <el-option label="OPTIONS" value="OPTIONS" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="状态码">
              <el-select
                v-model="searchForm.statusCode"
                placeholder="选择状态码"
                clearable
                style="width: 100%"
              >
                <el-option label="200" :value="200" />
                <el-option label="201" :value="201" />
                <el-option label="400" :value="400" />
                <el-option label="401" :value="401" />
                <el-option label="403" :value="403" />
                <el-option label="404" :value="404" />
                <el-option label="500" :value="500" />
                <el-option label="502" :value="502" />
                <el-option label="503" :value="503" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item>
              <el-button type="primary" @click="searchLogs">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    
    <!-- 统计信息 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="12" :sm="6">
        <div class="stat-item">
          <div class="stat-number">{{ totalLogs }}</div>
          <div class="stat-label">总日志数</div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6">
        <div class="stat-item">
          <div class="stat-number">{{ successLogs }}</div>
          <div class="stat-label">成功请求</div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6">
        <div class="stat-item">
          <div class="stat-number">{{ errorLogs }}</div>
          <div class="stat-label">失败请求</div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6">
        <div class="stat-item">
          <div class="stat-number">{{ formatBytes(totalTraffic) }}</div>
          <div class="stat-label">总流量</div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 日志列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="logs"
        style="width: 100%"
        :default-sort="{ prop: 'requestTime', order: 'descending' }"
      >
        <el-table-column prop="requestTime" label="请求时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.requestTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="proxyName" label="代理" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ row.proxyName }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="clientIp" label="客户端IP" width="140" />
        
        <el-table-column prop="method" label="方法" width="80">
          <template #default="{ row }">
            <el-tag :type="getMethodTagType(row.method)" size="small">
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="targetUrl" label="目标URL" min-width="200">
          <template #default="{ row }">
            <el-tooltip :content="row.targetUrl" placement="top">
              <div class="url-cell">{{ row.targetUrl }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column prop="statusCode" label="状态码" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.statusCode)" size="small">
              {{ row.statusCode }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="responseTime" label="响应时间" width="100">
          <template #default="{ row }">
            {{ formatResponseTime(row.responseTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="traffic" label="流量" width="100">
          <template #default="{ row }">
            {{ formatBytes(row.traffic) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showLogDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="600px"
    >
      <el-descriptions v-if="selectedLog" :column="1" border>
        <el-descriptions-item label="请求时间">
          {{ formatDateTime(selectedLog.requestTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="代理服务器">
          {{ selectedLog.proxyName }}
        </el-descriptions-item>
        <el-descriptions-item label="客户端IP">
          {{ selectedLog.clientIp }}
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">
          <el-tag :type="getMethodTagType(selectedLog.method)">
            {{ selectedLog.method }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="目标URL">
          <div class="url-text">{{ selectedLog.targetUrl }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="状态码">
          <el-tag :type="getStatusTagType(selectedLog.statusCode)">
            {{ selectedLog.statusCode }} - {{ getStatusCodeDescription(selectedLog.statusCode) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="响应时间">
          {{ formatResponseTime(selectedLog.responseTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="流量大小">
          {{ formatBytes(selectedLog.traffic) }}
        </el-descriptions-item>
        <el-descriptions-item label="User Agent" v-if="selectedLog.userAgent">
          <div class="user-agent-text">{{ selectedLog.userAgent }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Download,
  Refresh,
  Search,
  View
} from '@element-plus/icons-vue'
import { logApi, proxyApi } from '../api'
import {
  formatDateTime,
  formatBytes,
  formatResponseTime,
  getStatusCodeDescription
} from '../utils'
import type { AccessLog, ProxyConfig, LogQuery } from '../types'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const logs = ref<AccessLog[]>([])
const proxies = ref<ProxyConfig[]>([])
const selectedLog = ref<AccessLog | null>(null)
const dateRange = ref<[string, string] | null>(null)

const searchForm = reactive({
  proxyId: null as number | null,
  clientIp: '',
  method: '',
  statusCode: null as number | null
})

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 计算属性
const totalLogs = computed(() => pagination.total)

const successLogs = computed(() => {
  return logs.value.filter(log => log.statusCode >= 200 && log.statusCode < 400).length
})

const errorLogs = computed(() => {
  return logs.value.filter(log => log.statusCode >= 400).length
})

const totalTraffic = computed(() => {
  return logs.value.reduce((total, log) => total + log.traffic, 0)
})

// 方法
const loadLogs = async () => {
  try {
    loading.value = true
    
    const query: LogQuery = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    
    // 添加搜索条件
    if (searchForm.proxyId) query.proxyId = searchForm.proxyId
    if (searchForm.clientIp) query.clientIp = searchForm.clientIp
    if (searchForm.method) query.method = searchForm.method
    if (searchForm.statusCode) query.statusCode = searchForm.statusCode
    
    // 添加时间范围
    if (dateRange.value) {
      query.startDate = dateRange.value[0]
      query.endDate = dateRange.value[1]
    }
    
    const response = await logApi.getAccessLogs(query)
    
    if (response.code === 200) {
      logs.value = response.data.list
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('Failed to load logs:', error)
    ElMessage.error('加载日志失败')
  } finally {
    loading.value = false
  }
}

const loadProxies = async () => {
  try {
    const response = await proxyApi.getProxies()
    if (response.code === 200) {
      proxies.value = response.data
    }
  } catch (error) {
    console.error('Failed to load proxies:', error)
  }
}

const searchLogs = () => {
  pagination.page = 1
  loadLogs()
}

const resetSearch = () => {
  searchForm.proxyId = null
  searchForm.clientIp = ''
  searchForm.method = ''
  searchForm.statusCode = null
  dateRange.value = null
  
  pagination.page = 1
  loadLogs()
}

const refreshLogs = () => {
  loadLogs()
}

const exportLogs = () => {
  // 实现日志导出功能
  ElMessage.info('导出功能待实现')
}

const showLogDetail = (log: AccessLog) => {
  selectedLog.value = log
  detailDialogVisible.value = true
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadLogs()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadLogs()
}

const getMethodTagType = (method: string): string => {
  const typeMap: { [key: string]: string } = {
    GET: 'primary',
    POST: 'success',
    PUT: 'warning',
    DELETE: 'danger',
    HEAD: 'info',
    OPTIONS: 'info'
  }
  return typeMap[method] || 'info'
}

const getStatusTagType = (statusCode: number): string => {
  if (statusCode >= 200 && statusCode < 300) return 'success'
  if (statusCode >= 300 && statusCode < 400) return 'warning'
  if (statusCode >= 400 && statusCode < 500) return 'danger'
  if (statusCode >= 500) return 'danger'
  return 'info'
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadProxies(),
    loadLogs()
  ])
})
</script>

<style scoped>
.logs-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.page-title h2 {
  margin: 0 0 4px 0;
  font-size: 24px;
  color: #2c3e50;
}

.page-title p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 24px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.table-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.url-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.url-text {
  word-break: break-all;
  line-height: 1.5;
}

.user-agent-text {
  word-break: break-all;
  line-height: 1.5;
  font-size: 12px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .page-actions {
    width: 100%;
    display: flex;
    gap: 8px;
  }
  
  .page-actions .el-button {
    flex: 1;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .pagination-container {
    text-align: center;
  }
}
</style>